package com.example.springboot.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelImportUtil {

    public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) throws IOException {
        List<T> dataList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), clazz, new ExcelDataListener<>(dataList)).sheet().doRead();
        return dataList;
    }

    public static class ExcelDataListener<T> implements ReadListener<T> {

        private List<T> data;

        public ExcelDataListener(List<T> data) {
            this.data = data;
        }

        @Override
        public void invoke(T t, AnalysisContext analysisContext) {
            data.add(t);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            // 可以在这里添加读取完成后的操作
        }
    }

}